package com.hbu.fleastreet.controller.backend;

import com.hbu.fleastreet.entity.User;
import com.hbu.fleastreet.exception.LoginException;
import com.hbu.fleastreet.services.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 后端登陆，index页，退出等
 */
@Controller
@RequestMapping("/manager")
public class ManagerController {
    @Autowired
    private IUserService userService;


    /**
     * 访问首页
     *
     * @return
     */
    @GetMapping({"/index", "/index.html"})
    public String index() {
        return "backend/index";
    }

    /**
     * 访问登录页面
     *
     * @return
     */
    @GetMapping({"/login",""})
    public String login() {
        return "backend/login";
    }


    /**
     * 登录请求
     *
     * @param username
     * @param password
     */
    //@ResponseBody
    @PostMapping(value = "/login")
    public void login(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //登录成功 重定向到首页
        User user = userService.checkManagerLogin(username, password);
        if (user != null) {
            //登录成功 重定向到首页
            request.getSession().setAttribute("manager_user", user);
            response.sendRedirect("/fleastreet/manager/index");
        } else {
            throw new LoginException("登录失败！ 用户名或者密码错误");
        }
    }

    /**
     * 退出登录
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().removeAttribute("manager_user");
        response.sendRedirect("/fleastreet/manager/login");
    }
}
